<template>
<div class="auto-call-task-wrap">
  <div class="task-screen" v-show="currentPage === 'springScreen'">
      <springScreen
      @back="pageBack"
      :data="detailsData"
    ></springScreen>
 </div>
  <continer :showPage="showPage" :shadow="true" :pageshadow="true" :isNoTabs="true">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="pageChange(1)"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="fetchData">查询</el-button>
    </template>
    <template slot="content">
      <configTable
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        v-loading="showLoading"
        :headersConfig="false"
        ref="configTabel"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
              v-if="
                item.prop !== 'oprate' &&
                item.prop !== 'status' &&
                item.prop !== 'createUser' &&
                item.prop !== 'progress' &&
                item.prop !== 'connectionRate'
              "
            >
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'createUser' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop">{{ scope.row.createUser }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="80"
              v-if="item.prop === 'status' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop">{{ scope.row | getTaskStatus }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'progress' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <el-progress
                    style="width: 100px; margin-right: 8px"
                    :stroke-width="6"
                    :percentage="getProcess(scope.row)"
                    :show-text="false"
                  ></el-progress
                  ><span>{{ getFormat(scope.row) }}</span>
                </div>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="80"
              v-if="item.prop === 'connectionRate' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                {{ getConnectionRate(scope.row) }}%
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'oprate' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
              fixed="right"
              :width="50"
            >
              <template slot-scope="scope">
                <span class="oprate" @click="checkdDtails(scope.row)"
                  v-functions='["my_auto_call_task_list_view"]'
                  >查看</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
     </template>
    <template slot="page">
      <autoDetails
        @back="pageBack"
        typeProp="my"
        v-if="currentPage === 'details'"
        moduleType='myAutoOutCall'
        :data="detailsData"
      ></autoDetails>
    </template>
  </continer>
</div>
</template>

<script lang="ts">
import { Component, Watch, Mixins } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import { IvrData, PagingData, TabelHeaders } from '../components/callTaskCommon/types/index'

import autoDetails from '../components/callTaskCommon/autoDetails/index.vue'
import springScreen from '../components/callTaskCommon/springScreen/index.vue'
import taskMixin from '../components/callTaskCommon/task-mixin'
import { deepClone } from '@/utils/common'

@Component({
  name: 'myAutoCall',
  components: { continer, configTable, QuickSearch, autoDetails, springScreen }
})
export default class extends Mixins(taskMixin) {
  private $getCache: any
  private $route: any
  private $router: any
  private nextPage = ''
  private $confirm: any
  private currentCallObj: any = {}
  private showLoading: boolean = false
  private tempWatch: any = null

  private detailsData: any = {}

  private currentPage = ''

  // 详情控制
  private showPage: boolean = false

  private pagingData: PagingData = { total: 0, limit: 10, page: 1 }

  private tableHeaders: TabelHeaders[] = [
    {
      label: '任务名称',
      prop: 'name'
    },
    {
      label: '任务状态',
      prop: 'status'
    },
    {
      label: '优先级',
      prop: 'priority'
    },
    {
      label: '创建时间',
      prop: 'createTime',
      sortable: true
    },
    {
      label: '创建人',
      prop: 'createUserName'
    },
    {
      label: '任务进度',
      prop: 'progress'
    },
    {
      label: '接通率',
      prop: 'connectionRate'
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private checkHeaders: TabelHeaders[] = []
  private tableData: IvrData[] = []

  private stateOptions = [{
    name: '全部',
    _id: ''
  }, {
    name: '执行中',
    _id: 'dealing'
  }, {
    name: '暂停中',
    _id: 'pauseding'
  }, {
    name: '已暂停',
    _id: 'paused'
  }, {
    name: '已完成',
    _id: 'complete'
  }, {
    name: '已归档',
    _id: 'archived'
  }]

  private quickSearchForm = { // 快捷检索数据
    form: {
      name: '',
      statusList: []
    },
    advSearchOptions: [ // 快捷检索的数据
      { label: '任务名称', inputType: 'input', placeholder: '请输入任务名称', name: 'name', clearable: true },
      { label: '外呼任务状态', inputType: 'select', multiple: true, clearable: true, selectData: this.stateOptions, name: 'statusList' }
    ]
  }

  private updatePreviewData (data) {
    this.$set(this, 'detailsData', JSON.parse(JSON.stringify(data)))
  }

  private pageChange (page: number): void {
    this.pagingData.page = page
    this.fetchData()
  }

  private pageSizeChange (size: number): void {
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.fetchData()
  }

  private detailsToSpringScreen (callData: any) {
    const data = { url: `/call/action/autoCallTask/${callData.taskId}`, method: 'GET', data: {} }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success && res.data) {
        this.updatePreviewData(res.data || {})
        this.showPage = false
        this.nextPage = 'details'
        this.currentPage = 'springScreen'
        setTimeout(() => {
          this.$bus.$emit('initAutoCallTaskCall', { phone: callData.number, callSheetId: callData.superUniqueId, taskName: callData.taskName, memo: callData.memo })
        }, 50)
      }
    })
  }

  private checkdDtails (row: any) {
    this.currentPage = 'details'
    this.detailsData = row
    this.showPage = true
  }

  private checkHeadersChange (checkList): void {
    this.$set(this, 'checkHeaders', checkList)
  }

  private pageBack (type): void {
    if (type === 'springScreen') { // 弹屏返回到详情，要查一遍详情的数据
      const data = { url: `/call/action/autoCallTask/${this.currentCallObj.taskId}`, method: 'GET', hideLoading: true, data: {} }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res && res.success && res.data) {
          const agentObj = deepClone(this.$store.state.common.publicCache.userListObj)[res.data.createUser]
          const ivrObj = deepClone(this.$store.state.common.publicCache.ivrListObj)[res.data.ivrId]
          this.detailsData = res.data
          this.detailsData.createUserName = agentObj ? agentObj.name : '--'
          this.detailsData.ivrName = ivrObj ? ivrObj.name : '--'
        }
      })
    } else { // 详情的返回，查一遍列表
      this.fetchData()
    }
    if (this.nextPage) {
      this.currentPage = this.nextPage
      this.nextPage = ''
      this.showPage = true
      return
    }
    this.showPage = false
  }

  private fetchData (): void {
    this.showLoading = true
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page, type: 'my' }, this.quickSearchForm.form)
    const data = { url: '/call/action/autoCallTask/list', method: 'POST', hideLoading: true, data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success) {
        const resList = res.list || []
        if (resList.length === 0) {
          const page = Math.ceil(res.count / this.pagingData.limit)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.fetchData()
            return false
          }
        }
        resList.forEach((item: any) => {
          const agentObj = deepClone(this.$store.state.common.publicCache.userListObj)[item.createUser]
          item.createUserName = agentObj ? agentObj.name : '--'
          const ivrObj = deepClone(this.$store.state.common.publicCache.ivrListObj)[item.ivrId]
          item.ivrName = ivrObj ? ivrObj.name : '--'
        })
        this.tableData = resList
        this.pagingData.total = res.count || 0
      }
      this.showLoading = false
    }).catch(() => {
      this.tableData = []
      this.pagingData.total = 0
      this.showLoading = false
    })
  }

  get autoCallTaskData (): any {
    return deepClone(this.$store.state.cti.autoCallTaskData)
  }

  @Watch('autoCallTaskData')
  private autoCallTaskDataChange (callObj, oldObj) {
    if (Object.keys(callObj).length <= 0 || (callObj.superUniqueId === oldObj.superUniqueId)) { // 当前没有数据 || 当前的ID和之前的ID一致，不出弹屏
      return false
    }
    const type = this.$route.path.split('/')[1]
    if (type !== 'call_task') {
      this.tempWatch = callObj
      return false
    }
    this.tempWatch = null
    this.currentCallObj = callObj
    this.detailsToSpringScreen(callObj)
  }

  private beforeMount () {
    this.$getCache('/call/action/general/query', ['ivrList'], true).then((res: any) => {
      this.fetchData()
    })
  }

  private mounted () { // 触发弹屏的代码不能写在beforeMount中，容易偶发qiankun盒子加载失败
    this.$nextTick(() => {
      const callObj = this.$store.state.cti.autoCallTaskData || {}
      this.currentCallObj = callObj
      if (callObj.taskId) {
        this.detailsToSpringScreen(callObj)
      }
    })
  }

  private activated () {
    // 组件被重新激活,再查询一次列表
    this.fetchData()
    if (this.tempWatch) {
      // 在别的模块，触发了自动外呼（watch）,切换回来的时候再次复制，如果是在watch中执行，会导致
      this.$nextTick(() => {
        this.currentCallObj = this.tempWatch
        this.detailsToSpringScreen(this.tempWatch)
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.oprate
  color $c-main
  margin-right 10px
  cursor pointer
.oprate:hover
  opacity 0.8
.auto-call-task-wrap
  width 100%
  height 100%
  position relative
.task-screen
  border 1px solid #ecf0f3
  box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
  border-radius 10px
  overflow hidden
  position absolute
  width 100%
  height 100%
  left 0
  top 0
  z-index 1000
  background #fff
</style>
